package com.xyh.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class ServiceConsumerController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/callService")
    public String callService() {
        // 直接调用服务 可行
//        return restTemplate.getForObject("http://localhost:8000/hello", String.class);

        // 通过服务发现调用服务 不可行
        List<ServiceInstance> instances;
        int retries = 5; // 重试次数
        while (retries-- > 0) {
            instances = discoveryClient.getInstances("user-service");
            if (instances != null && !instances.isEmpty()) {
                String serviceUri = instances.get(0).getUri().toString();
                return restTemplate.getForObject(serviceUri + "/login", String.class);
            }
            try {
                Thread.sleep(2000); // 等待2秒后重试
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        return "Service not available";
    }

}